package com.zxy.controller;

import com.zxy.common.result.PageResult;
import com.zxy.common.result.Result;
import com.zxy.pojo.dto.ClueFalseDto;
import com.zxy.pojo.dto.CluePageQueryDto;
import com.zxy.pojo.entity.Clue;
import com.zxy.pojo.vo.AssignmentVo;
import com.zxy.service.ClueService;
import com.zxy.service.ClueTrackRecordService;
import com.zxy.util.OperLog;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/clues")
@Slf4j
public class ClueController {
    @Autowired
    private ClueService clueService;

    @Autowired
    private HttpServletRequest request;

    /**
     * 查询线索管理列表
     */
    @OperLog(title = "查询线索管理列表", businessType = 0, saveParams = true)
    @RequestMapping("/clue/list")
    public Map<String, Object> list(CluePageQueryDto dto) {
        log.info("查询线索列表，参数: {}", dto);
        if (dto.getPageNum() == null || dto.getPageNum() <= 0) {
            dto.setPageNum(1);
        }
        if (dto.getPageSize() == null || dto.getPageSize() <= 0) {
            dto.setPageSize(10);
        }

        PageResult pageResult = clueService.selectCluelist(dto);

        Map<String, Object> result = new HashMap<>();
        result.put("total", pageResult.getTotal());
        result.put("rows", pageResult.getRows());
        result.put("code", 200);
        result.put("msg", "查询成功");
        result.put("params", null);

        log.info("查询线索列表成功，返回记录数: {}", pageResult.getTotal());

        return result;
    }

    /**
     * 新增线索
     */
    @OperLog(title = "新增线索", businessType = 1, saveParams = true, saveResult = true)
    @PostMapping("/clue")
    public Result add(@RequestBody Clue clue) {
        log.info("添加线索，参数: {}", clue);

        // 从session中获取当前用户名
        String currentUsername = (String) request.getSession().getAttribute("username");

        if (currentUsername == null) {
            currentUsername = "admin";
        }
        clue.setCreateBy(currentUsername);
        clue.setAssignBy(currentUsername);
        // 设置用户ID
//        clue.setUserId(1L);
        clue.setOwnerTime(new Date());
        return clueService.add(clue);
    }

    /**
     * 获取线索详细信息
     */
    @OperLog(title = "获取线索详细信息", businessType = 0, saveParams = true)
    @GetMapping("/clue/{id}")
    public Result getInfo(@PathVariable("id") Long id){
        log.info("获取线索详细信息，参数: {}", id);
        return Result.success(clueService.selectClueById(id));
    }

    /**
     * 线索池分页查询
     */
    @OperLog(title = "线索池分页查询", businessType = 0, saveParams = true)
    @RequestMapping("/clue/pool")
    public Map<String, Object> pageQuery(CluePageQueryDto dto) {
        log.info("线索池分页查询： {}", dto);

        if (dto.getPageNum() == null || dto.getPageNum() <= 0) {
            dto.setPageNum(1);
        }
        if (dto.getPageSize() == null || dto.getPageSize() <= 0) {
            dto.setPageSize(10);
        }

        PageResult pageResult = clueService.cluePoolPageQuery(dto);

        Map<String, Object> result = new HashMap<>();
        result.put("total", pageResult.getTotal());
        result.put("rows", pageResult.getRows());
        result.put("code", 200);
        result.put("msg", "查询成功");
        result.put("params", null);

        log.info("查询线索列表成功，返回记录数: {}", pageResult.getTotal());
        return result;
    }

    /**
     * 分配线索
     */
    @OperLog(title = "分配线索", businessType = 2, saveParams = true, saveResult = true)
    @PutMapping("/clue/assignment")
    public Result assignment(@RequestBody AssignmentVo assignmentVo, HttpServletRequest request) {
        log.info("分配线索，参数: {}", assignmentVo);
        // 从session中获取当前操作用户名
        String currentUsername = (String) request.getSession().getAttribute("username");
        if (currentUsername == null) {
            currentUsername = "admin";
        }
        String result = clueService.assignment(assignmentVo.getIds(), assignmentVo.getUserId());

        return Result.success(result);

    }

    /**
     * 伪线索
     */
    @OperLog(title = "标记伪线索", businessType = 2, saveParams = true, saveResult = true)
    @PutMapping("/clue/false/{id}")
    public Result markAsFalseClue(@PathVariable Long id, @RequestBody ClueFalseDto dto) {
        log.info("标记为伪线索，路径参数id: {}, dto: {}", id, dto);
        return clueService.markAsFalseClue(dto, id);
    }

    /**
     * 捞取线索
     */
    @OperLog(title = "捞取线索", businessType = 2, saveParams = true, saveResult = true)
    @PutMapping("/clue/gain")
    public Result gainClue(@RequestBody Map<String, Object> request) {
        log.info("捞取线索请求参数: {}", request);

        // 获取线索ID数组第一个
        List<?> idsList = (List<?>) request.get("ids");
        Long id = Long.parseLong(idsList.get(0).toString());

        log.info("捞取线索，线索ID: {}", id);
        return clueService.gainClue(id);
    }

    /**
     * 线索转商机
     */
    @OperLog(title = "线索转商机", businessType = 2, saveParams = true, saveResult = true)
    @PutMapping("/clue/changeBusiness/{id}")
    public Result changeBusiness(@PathVariable Long id) {
        log.info("线索转商机，参数: {}", id);
        return clueService.changeBusiness(id);
    }

}
